package com.active.test.queue.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;

import javax.jms.*;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-08-26 下午5:34
 */
@Slf4j
public class JmsProduce {

    private static final String ACTIVEMQ_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "queue01";

    public static void main(String[] args) throws JMSException {
        //1.创建连接工厂，按照给定的url地址，采用默认用户名和密码
        final ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        // 显示配置采用异步发送方式
        activeMQConnectionFactory.setUseAsyncSend(true);

        //2.通过连接工厂，获取连接的connection
        final Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3.创建会话
        // 两个参数，第一个叫事务，第二个叫签收
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //4.创建目的地（具体是队列还是主题）
        final Queue destination = session.createQueue(QUEUE_NAME);

        //5.创建消息的生产者
//        final MessageProducer producer = session.createProducer(destination);
//        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        // 采用消息回调,保证异步消息发送成功
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(destination);

        //6.通过使用消息生产者，生产3条消息发送到MQ的队列里
        for (int i = 0; i < 3; i++) {
            //7.创建消息
            // textMessage可以理解为一个字符串
            final TextMessage textMessage = session.createTextMessage("msg----" + i);
            // 增加一个属性
//            textMessage.setStringProperty("c01", "vip");

            // 保证异步消息发送成功:设置一个消息头
            textMessage.setJMSMessageID(UUID.randomUUID().toString() + "--order atguigu");
            final String jmsMessageID = textMessage.getJMSMessageID();
            //通过producer发送给MQ
            producer.send(textMessage, new AsyncCallback() {
                @Override
                public void onSuccess() {
                    log.info(jmsMessageID + " has been successfully sent");
                }

                @Override
                public void onException(JMSException exception) {
                    log.warn(jmsMessageID + " has been failed to send");
                }
            });
        }

        //9关闭资源
        producer.close();
        session.close();
        connection.close();

        log.info("消息发布到mq完成");
    }
}
